package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"database/sql"
	"encoding/base64"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"math/rand"
	"os"
	"time"
)

var SaasYcgDb *gorm.DB

func init() {
	SaasYcgDb = connectYcg()
}

func connectYcg() *gorm.DB {
	var err error
	//连接数据库
	//SaasYcgDb, err = gorm.Open("mysql", "8bc6dd9b-8f37-43db-b9c1-5d01db10066d:g260fR6KUx4yXNfz@tcp(audit.mingyuanyun.com:30208)/gfyx_ycg?charset=utf8mb4&parseTime=true")
	//dsn := fmt.Sprintf("wengg01@292:718c17e736f7795e546ef3e89fe96257@(dbproxy.mysre.cn:13366)/gfyx_ycg?charset=utf8mb4&parseTime=true") //生产环境
	dsn := fmt.Sprintf("root:E8aisygkcvT3@(rm-wz9yi3c0jl9n118938o.mysql.rds.aliyuncs.com:3306)/gfyx_ycg?charset=utf8mb4&parseTime=true") //测试环境
	//dsn := fmt.Sprintf("root:qziCSjIG3HGtdoXx@(rm-uf670dh81953650b55o.mysql.rds.aliyuncs.com:3306)/gfyx_ycg?charset=utf8mb4&parseTime=true") //预发布环境
	SaasYcgDb, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("数据库连接成功")

	SaasYcgDb = SaasYcgDb.Debug()

	return SaasYcgDb
}

type TenantsInstance struct {
	Id             int32        `json:"id"`
	Host           string       `json:"host"`
	Port           int32        `json:"port"`
	DbName         string       `json:"db_name"`
	Username       string       `json:"username"`
	Password       string       `json:"password"`
	ReaderUsername string       `json:"reader_username"`
	ReaderPassword string       `json:"reader_password"`
	TenantCode     string       `json:"tenant_code"`
	DbExtras       string       `json:"db_extras"`
	CreatedBy      string       `json:"created_by"`
	CreatedOn      sql.NullTime `json:"created_on"`
	ModifiedBy     string       `json:"modified_by"`
	ModifiedOn     sql.NullTime `json:"modified_on"`
	IsDeleted      int32        `json:"is_deleted"`
}

// go run jobs/db.go

func main() {
	sqlText := ""
	errText := ""
	tenantList := make([]TenantsInstance, 0)
	err := SaasYcgDb.Table("tenant_config_service.tenants_instance").Find(&tenantList).Error
	if err != nil {
		errText += err.Error() + "\n"
		fmt.Printf("查询租户实例数据,err:%s", err.Error())
	}

	for _, v := range tenantList {
		if v.ModifiedBy == "历史数据同步" {
			modified_by := "pwd:" + v.Password + "且read_pwd:" + v.ReaderPassword
			newPwd, err := EncryptByAes(v.Password)
			if err != nil {
				errText += err.Error() + "\n"
			}
			newReadPwd, err := EncryptByAes(v.ReaderPassword)
			if err != nil {
				errText += err.Error() + "\n"
			}

			sqlText += fmt.Sprintf("update `%s`.`tenants_instance` set `password`='%s',`reader_password`='%s',`db_extras`='%s' where  id=%d;", "tenant_config_service", newPwd, newReadPwd, modified_by, v.Id)
			sqlText += "\n"
		}

	}

	outputFile(sqlText, "tenants_instance.sql")
	outputFile(errText, "err.sql")
}

func outputFile(str string, fileName string) {
	fileName = "./jobs/password/" + fileName
	dstFile, err := os.Create(fileName)
	if err != nil {
		fmt.Println(err.Error())
	}
	if dstFile != nil {
		defer dstFile.Close()
		dstFile.WriteString(str)
	}

}

//加密过程：
//  1、处理数据，对数据进行填充，采用PKCS7（当密钥长度不够时，缺几位补几个几）的方式。
//  2、对数据进行加密，采用AES加密方法中CBC加密模式
//  3、对得到的加密数据，进行base64加密，得到字符串
// 解密过程相反

// 16,24,32位字符串的话，分别对应AES-128，AES-192，AES-256 加密方法
const PwdKey = "1234567812345678"

// pkcs7Padding 填充
func pkcs7Padding(data []byte, blockSize int) []byte {
	//判断缺少几位长度。最少1，最多 blockSize
	padding := blockSize - len(data)%blockSize
	//补足位数。把切片[]byte{byte(padding)}复制padding个
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padText...)
}

// pkcs7UnPadding 填充的反向操作
func pkcs7UnPadding(data []byte) ([]byte, error) {
	length := len(data)
	if length == 0 {
		return nil, errors.New("加密字符串错误！")
	}
	//获取填充的个数
	unPadding := int(data[length-1])
	return data[:(length - unPadding)], nil
}

// AesEncrypt 加密
func AesEncrypt(data []byte, key []byte) ([]byte, error) {
	//创建加密实例
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	//判断加密快的大小
	blockSize := block.BlockSize()
	//填充
	encryptBytes := pkcs7Padding(data, blockSize)
	//初始化加密数据接收切片
	crypted := make([]byte, len(encryptBytes))
	//使用cbc加密模式
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	//执行加密
	blockMode.CryptBlocks(crypted, encryptBytes)
	return crypted, nil
}

// AesDecrypt 解密
func AesDecrypt(data []byte, key []byte) ([]byte, error) {
	//创建实例
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	//获取块的大小
	blockSize := block.BlockSize()
	//使用cbc
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	//初始化解密数据接收切片
	crypted := make([]byte, len(data))
	//执行解密
	blockMode.CryptBlocks(crypted, data)
	//去除填充
	crypted, err = pkcs7UnPadding(crypted)
	if err != nil {
		return nil, err
	}
	return crypted, nil
}

// EncryptByAes Aes加密 后 base64 再加
func EncryptByAes(data string) (string, error) {
	res, err := AesEncrypt([]byte(data), []byte(PwdKey))
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(res), nil
}

// DecryptByAes Aes 解密
// PwdKey 密钥
func DecryptByAes(data string) (string, error) {
	dataByte, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return "", err
	}
	res, err := AesDecrypt(dataByte, []byte(PwdKey))
	return string(res), err
}

func CreateDbRandPwd(tenantDbName string) string {
	rand.Seed(time.Now().UnixNano()) // 设置随机种子
	passwordLength := 6              // 密码长度
	// 定义密码字符集
	charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	// 生成随机密码
	password := make([]byte, passwordLength)
	for i := 0; i < passwordLength; i++ {
		password[i] = charset[rand.Intn(len(charset))]
	}
	return tenantDbName + "_" + string(password) //数据库名称+随机数
}
